// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const db = uniCloud.database();
const dep = db.collection('department');
const job = db.collection('job')
const role = db.collection('roles')


const appid = 'wx24217312b37b9544'
const secret = '51d07edcd8bfd9c196a16c12ad482b64'
const js_code = '0c346o0w35AYA43vmU2w3oiXuT246o0C'
const openid = 'oNx356_5ngN6LkpYzIvtnSYRS4Dk'
const templateid = 'DIKykgYuQNJ9iDbpOMtxVFCoptZD-370j93kRS_sI6A'
const access_token =
	"90_W2eL2DQyceiUfdMaM83X3153PAbEVxQwhrO9p4nhde6-UsDlEwuIjRsv0WOq4hnhnpaDW9UMLN6cbSSCEWRrtq9kTF7QTbBtMJxcnG1TZQn9Jy44STqm2N2zHYkLHZfAIAQME"



async function get_wx_access_token() {

	return uniCloud.request({
		method: 'get',
		// appip和secret需要去小程序管理界面查看
		url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`,
		dataType: 'json',
		timeout: 30000
	}).then(res => {
		if (res.statusCode == 200) {
			return {
				access_token: res.data.access_token,
				expires_in: res.data.expires_in
			}
			//{access_token:res.data.access_token,expires_in:res.data.expires_in}
		}
	})
}

// wxappid wxsecret为小程序的appId和secretKey，登录小程序后台可查看，code就是user_login的那个code
async function get_openid(js_code) {

	// 调用微信接口
	const res = await uniCloud.httpclient.request(
		`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${js_code}&grant_type=authorization_code`, {
			dataType: 'json'
		}
	);

	if (res.data.errcode) {
		throw new Error(`微信接口错误: ${res.data.errmsg}`);
	}

	return {
		openid: res.data.openid,
		session_key: res.data.session_key
	};
}



async function isDepExist(name) {
	try {
		const res = await dep.where({
			name: name
		}).get(); // 添加 await
		return res.data.length > 0; // 存在返回 true，否则 false
	} catch (error) {
		return false; // 错误时视为不存在
	}
}

async function isJobExist(name) {
	try {
		const res = await job.where({
			name: name
		}).get(); // 添加 await
		return res.data.length > 0; // 存在返回 true，否则 false
	} catch (error) {
		return false; // 错误时视为不存在
	}
}

async function isRoleExist(role_name) {
	try {
		const res = await role.where({
			role_name: role_name
		}).get(); // 添加 await
		return res.data.length > 0; // 存在返回 true，否则 false
	} catch (error) {
		return false; // 错误时视为不存在
	}
}

module.exports = {

	async notice(event) {
		// 下方的thing1，thing2和其他，对应的是你选取模板的模板详情中的字段名称(可在小程序后台模板查看对应的字段，要和上面的字段一样)，需要更改成你自己的
		const pushmsg = {
			"touser": openid,
			"template_id": templateid,
			"data": {
				"time4": {
					"value": "2025-3-21 10:00"
				},
				"number5": {
					"value": "5"
				},
				"thing8": {
					"value": "吉安"
				},
				"thing2": {
					"value": "郑春文"
				},
				"phone_number3": {
					"value": "13522343234"
				}
			},
			"page": "pagesA/car/schedules_list"
		}
		return uniCloud.request({
			// 此处的mytoken
			url: `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${access_token}`,
			data: JSON.stringify(pushmsg),
			method: 'POST',
			success: function(res) {
				// // //console.log('success');

			}
		})
	},

	async getaccess_token(event) {
		let access_token = await get_wx_access_token()
		return {
			access_token: access_token
		}
	},

	async getopenid(event) {
		let data = await get_openid(event.js_code)
		return data
	},

	async queryBarcode(event) {
		try {
			// 使用uniCloud内置httpclient
			const appcode = '6a8213a375a843ff88e27f1c08e4887a'
			const {
				status,
				data
			} = await uniCloud.httpclient.request(
				'https://jisutxmcx.market.alicloudapi.com/barcode2/query', {
					method: 'POST',
					contentType: 'application/x-www-form-urlencoded', // 重要：声明表单格式
					headers: {
						"Authorization": `APPCODE ${appcode}`
					},
					data: {
						barcode: event.barcode
					},
					dataType: 'json' // 自动解析响应为JSON
				}
			);

			// 处理非200响应
			if (status !== 200) {
				throw new Error(`API响应异常，状态码：${data}`);
			}
			//返回了错误码
			if (data.status != 0) {
				return {
					code: data.status,
					message: data.msg
				}
			}

			return {
				code: 0,
				data: data.result,
				message: '查询成功'
			};
		} catch (error) {
			//console.error('发送失败:', error);
			return {
				statusCode: 500,
				message: '发送失败',
				body: {
					code: -1,
					message: '发送失败',
					error: error.message || '未知错误'
				}
			};
		}
	},

	async getjobselect(event, content) {
		const res = await job.field(event.field).where(event.data).orderBy("sort", "asc").get()
		if (res.data) {
			return {
				code: 0,
				message: '查询成功',
				data: res.data
			}
		} else {
			return {
				code: -1,
				message: '查询失败',
			}
		}
	},

	async getdepselect(event, content) {
		const res = await dep.field(event.field).where(event.data).orderBy("sort", "asc").get()
		if (res.data) {
			return {
				code: 0,
				message: '查询成功',
				data: res.data
			}
		} else {
			return {
				code: -1,
				message: '查询失败',
			}
		}
	},
	async getroleselect(event, content) {
		const res = await role.field(event.field).where(event.data).orderBy("sort", "asc").get()
		if (res.data) {
			return {
				code: 0,
				message: '查询成功',
				data: res.data
			}
		} else {
			return {
				code: -1,
				message: '查询失败',
			}
		}
	},
	//组织架构相关
	async getDepartment(event, content) {
		try {
			const res = await dep.where(event).orderBy("sort", "asc").get()
			if (res.data) {
				return {
					code: 0,
					message: '查询成功',
					data: res.data
				}
			} else {
				return {
					code: -1,
					message: '查询失败',
				}
			}
		} catch (e) {
			return {
				code: -1,
				message: '查询失败',
			}
		}
	},



	async addDepartment(event) {
		const exists = await isDepExist(event.name);
		if (exists) {
			return {
				code: 1,
				message: '部门名称已存在'
			};
		}

		try {
			// 添加创建时间戳
			event.create_date = new Date();
			const res = await dep.add(event);
			return {
				code: 0,
				message: '添加成功',
				data: res
			};
		} catch (e) {
			return {
				code: -1,
				message: '添加失败: ' + e.message
			};
		}
	},

	async updateDepartment(event) {
		const id = event._id;
		if (!id) {
			return {
				code: -1,
				message: '缺少部门ID'
			};
		}

		// 检查名称是否重复 (排除自身)
		const existing = await dep.where({
			name: event.name,
			_id: db.command.neq(id)
		}).get();

		if (existing.data.length > 0) {
			return {
				code: 1,
				message: '部门名称已被其他部门使用'
			};
		}

		try {
			// 移除ID字段避免更新冲突
			delete event._id;
			// 添加更新时间戳
			event.update_date = new Date();

			const res = await dep.doc(id).update(event);
			return {
				code: 0,
				message: '更新成功',
				updated: res.updated // 返回更新数量
			};
		} catch (e) {
			return {
				code: -1,
				message: '更新失败: ' + e.message
			};
		}
	},

	// 按ID获取部门详情 (新增方法)
	async getDepartmentById(id) {
		try {
			const res = await dep.doc(id).get();
			if (res.data && res.data.length > 0) {
				return {
					code: 0,
					message: '查询成功',
					data: res.data[0] // 返回单条部门数据
				};
			}
			return {
				code: 404,
				message: '部门不存在'
			};
		} catch (e) {
			return {
				code: -1,
				message: '查询失败: ' + e.message
			};
		}
	},

	//职务
	async getJob(event, content) {
		try {
			const res = await job.where(event).orderBy("sort", "asc").get()
			if (res.data) {
				return {
					code: 0,
					message: '查询成功',
					data: res.data
				}
			} else {
				return {
					code: -1,
					message: '查询失败',
				}
			}
		} catch (e) {
			return {
				code: -1,
				message: '查询失败',
			}
		}
	},
	
	
	
	async addJob(event) {
		const exists = await isJobExist(event.name);
		if (exists) {
			return {
				code: 1,
				message: '职务名称已存在'
			};
		}
	
		try {
			// 添加创建时间戳
			event.create_date = new Date();
			const res = await job.add(event);
			return {
				code: 0,
				message: '添加成功',
				data: res
			};
		} catch (e) {
			return {
				code: -1,
				message: '添加失败: ' + e.message
			};
		}
	},
	
	async updateJob(event) {
		const id = event._id;
		if (!id) {
			return {
				code: -1,
				message: '缺少职务ID'
			};
		}
	
		// 检查名称是否重复 (排除自身)
		const existing = await job.where({
			name: event.name,
			_id: db.command.neq(id)
		}).get();
	
		if (existing.data.length > 0) {
			return {
				code: 1,
				message: '职务名称已被使用'
			};
		}
	
		try {
			// 移除ID字段避免更新冲突
			delete event._id;
			// 添加更新时间戳
			event.update_date = new Date();
	
			const res = await job.doc(id).update(event);
			return {
				code: 0,
				message: '更新成功',
				updated: res.updated // 返回更新数量
			};
		} catch (e) {
			return {
				code: -1,
				message: '更新失败: ' + e.message
			};
		}
	},
	
	// 按ID获取职务详情 (新增方法)
	async getJobById(id) {
		try {
			const res = await job.doc(id).get();
			if (res.data && res.data.length > 0) {
				return {
					code: 0,
					message: '查询成功',
					data: res.data[0] // 返回单条数据
				};
			}
			return {
				code: 404,
				message: '职务不存在'
			};
		} catch (e) {
			return {
				code: -1,
				message: '查询失败: ' + e.message
			};
		}
	},

	//权限相关
	async getRole(event, content) {
		try {
			const res = await role.where(event).orderBy("role_id", "desc").get()
			if (res.data) {
				return {
					code: 0,
					message: '查询成功',
					data: res.data
				}
			} else {
				return {
					code: -1,
					message: '查询失败',
				}
			}
		} catch (e) {
			return {
				code: -1,
				message: '查询失败',
			}
		}
	},



	async addRole(event) {
		const exists = await isRoleExist(event.name);
		if (exists) {
			return {
				code: 1,
				message: '权限名称已存在'
			};
		}

		try {
			// 添加创建时间戳
			event.create_date = new Date();
			const res = await role.add(event);
			return {
				code: 0,
				message: '添加成功',
				data: res
			};
		} catch (e) {
			return {
				code: -1,
				message: '添加失败: ' + e.message
			};
		}
	},

	// 更新部门 (新增方法)
	async updateRole(event) {
		const id = event._id;
		if (!id) {
			return {
				code: -1,
				message: '缺少权限ID'
			};
		}

		// 检查名称是否重复 (排除自身)
		const existing = await role.where({
			role_name: event.role_name,
			_id: db.command.neq(id)
		}).get();

		if (existing.data.length > 0) {
			return {
				code: 1,
				message: '权限名称已被使用'
			};
		}

		try {
			// 移除ID字段避免更新冲突
			delete event._id;
			// 添加更新时间戳
			event.update_date = new Date();

			const res = await role.doc(id).update(event);
			return {
				code: 0,
				message: '更新成功',
				updated: res.updated // 返回更新数量
			};
		} catch (e) {
			return {
				code: -1,
				message: '更新失败: ' + e.message
			};
		}
	},

	// 按ID获取部门详情 (新增方法)
	async getRoleById(id) {
		try {
			const res = await role.doc(id).get();
			if (res.data && res.data.length > 0) {
				return {
					code: 0,
					message: '查询成功',
					data: res.data[0] // 返回单条部门数据
				};
			}
			return {
				code: 404,
				message: '部门不存在'
			};
		} catch (e) {
			return {
				code: -1,
				message: '查询失败: ' + e.message
			};
		}
	},



	_before: function() { // 通用预处理器

	},
	/**
	 * method1方法描述
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 */
	/* 
	method1(param1) {
		// 参数校验，如无参数则不需要
		if (!param1) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '参数不能为空'
			}
		}
		// 业务逻辑
		
		// 返回结果
		return {
			param1 //请根据实际需要返回值
		}
	}
	*/
}